<?php
/*
// +----------------------------------------------------------------------------------------
// | Icoterie Development Framework Intelligence Enterprise Management Priority Selective
// +----------------------------------------------------------------------------------------
// | Copyright (c) [2019] [Honor Full Epoch Educational Science Technology Hebei Co., Ltd.]
// | website  http://dev.icoterie.top http://www.ihfe.top
// +----------------------------------------------------------------------------------------
// | [Icoterie Development Framework] is licensed under the Mulan PSL v2.
// +----------------------------------------------------------------------------------------
// | You can use this software according to the terms and conditions of the Mulan PSL v2.
// +----------------------------------------------------------------------------------------
// | Licensed ( http://license.coscl.org.cn/MulanPSL2 )
// +----------------------------------------------------------------------------------------
// | THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
// | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
// | FIT FOR A PARTICULAR PURPOSE.
// +----------------------------------------------------------------------------------------
// | See the Mulan PSL v2 for more details.
// +----------------------------------------------------------------------------------------
// | Author: Reflux Lewse,Red Shadow Sue
// +----------------------------------------------------------------------------------------
// | 核心调度类
// +----------------------------------------------------------------------------------------
*/
namespace core\basic;
use core\basic\Service;
use core\basic\Config;
use core\basic\Response;
class Kernel{
	public function __construct()
    {
		new Service();//启动服务
	}
    public function run(){
		$path_info = self:: getPathInfo();//获取地址
		$path_info = self:: urlBlind($path_info);//地址绑定
		$path_info = self:: urlRoute($path_info);//地址路由
		$access_path = self:: getAccessPath($path_info);//访问路径
		$controllerPath = self:: regAppPath($access_path);//应用路径
		self:: loadComm();//应用加载
		self:: loadController($controllerPath);//控制器路径	
    }
	/** 
	* 获取地址 
	* @echo string	$p 访问地址
	*/
	private static function getPathInfo() 
	{
		//$p = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] :'/'));
		$pt = Config::get('app','ut') ?: 1;
		switch ($pt) {
            case '2':
               $p = '/' . (isset($_REQUEST['m'])?$_REQUEST['m']:'') . '/' . (isset($_REQUEST['c'])?$_REQUEST['c']:'') . '/' . (isset($_REQUEST['a'])?$_REQUEST['a']:'');  
                break;
            case '3':
				$p = isset($_REQUEST['p'])?$_REQUEST['p']:'///';
                break;
            default:
                $p = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
        }
		if(isset($p)){
			if(! mb_check_encoding($p, 'UTF-8')){
				$p = mb_convert_encoding($p, 'utf-8', 'GBK');
			}else if(strpos($p,$_SERVER['SCRIPT_NAME']) !== false){
				$p = str_replace('index.php', '', $p);
			}
			if(strpos($p,Config::get('app','us')) !== false){
				$p = str_replace((Config::get('app','us')?:'.html'), '', $p);
			}else if(strpos($p,'.') !== false){
				echo '访问地址错误';exit;
			}
		}
		return $p;
	}
	/** 
	* 地址绑定 
	* @param string	$p 访问地址
	* @echo string	$p 访问地址
	*/
	private static function urlBlind($p) 
	{
		$l = Config::get('location');
		$d = $_SERVER['HTTP_HOST'];
		foreach ($l as $k=>$v){
			if ($v == $d){
				$l = $v;
				break;
			}
		}
		if (is_array($l)){
			echo '访问域名未绑定，请核对！';die();
		}
		return $p;
	}
	/** 
	* 地址路由 
	* @param string	$p 访问地址
	* @echo string	$p 访问地址
	*/
	private static function urlRoute($p) 
	{
		$a = explode('/', substr($p, 1));
		if (Config::get('app','mm') == 'false') {
			$m = MODULE ?: Config::get('app','dm');
		} else {
			$m = isset($a[0]) && $a[0] != '' ? $a[0] : Config::get('app','dm');
			if(strpos(Config::get('app','am'),strtolower($m)) == false){
				echo '模型未许可';exit;
			}
		}
		define('D_M', strtolower($m));
		$r = Config::get('route', D_M);
		foreach ($r as $k=>$v) 
		{
			if(strpos($p,$k) !== false){
				$p = str_replace($k,$v,$p);
				break;
			}
		}
		return substr($p, 1);
	}
	private static function getAccessPath($p) 
	{
		$a = explode('/', $p);
		if (Config::get('app','mm') == 'false') {
			$a[0] = isset($a[0]) && $a[0] != '' ? $a[0] : Config::get('app','dc');
			$a[1] = isset($a[1]) && $a[1] != '' ? $a[1] : Config::get('app','da');
			$t['c'] = $a[0];
			$t['f'] = $a[1];
		} else {
			$a[1] = isset($a[1]) && $a[1] != '' ? $a[1] : Config::get('app','dc');
			$a[2] = isset($a[2]) && $a[2] != '' ? $a[2] : Config::get('app','da');
			$t['c'] = $a[1];
			$t['f'] = $a[2];
			$m = array_shift($a);
			$p = implode('/',$a);
			
		}
		if(strpos($t['c'],'@') !== false){
			$f = explode('@', $t['c']);
			$t['c'] = $f[0];
			$t['f'] = $f[1];
			$p = str_replace('@','/',$p);
		}
		if(strpos($t['c'],'.') !== false){
			$t['c'] = str_replace('.','/',$t['c']);
			$p = str_replace('.','/',$p);
		}
		if(strpos($p,implode('/',$t)) !== false){
			$t['p'] = substr(str_replace(implode('/',$t),'',$p),1);
		}
		return $t;
	}
	/** 
	* 应用路径 
	* @param string	$a['c']	控制器
	* @param string	$a['f']	方法
	* @param string	$a['p']	参数
	* @echo string	
	*/
	private static function regAppPath($a) 
	{
		define('APP_CONTROLLER', 'app' . DS . D_M  . DS . 'control' . DS);
		$m = APP_PATH . D_M . DS;
		define('APP_CONTROLLER_PATH', $m . 'control' . DS);
		define('APP_MODEL_PATH', $m . 'model'  . DS);
		if(Config::get('app','mm') == 'false' || D_M == 'admin'){
			define('APP_VIEW_PATH', $m . 'view' . DS);
		}else{
			$t = 'template';
			if(Config::get('app','dt')){
				$t .= DS . Config::get('app','dt');
			}
			if(Config::get('app','dh')){
				$t .= DS . Config::get('app','dh');
			}
			defined('APP_VIEW_PATH') ?: define('APP_VIEW_PATH', SITES_ROOT . $t . DS);
		}
		define('APP_COMMON_PATH', APP_PATH . 'common'  . DS);
		Response::checkDir(APP_CONTROLLER_PATH);
		Response::checkDir(APP_MODEL_PATH);
		Response::checkDir(APP_VIEW_PATH);
		Response::checkDir(APP_COMMON_PATH);
		Response::checkFile(APP_COMMON_PATH . D_M . 'Controller.php');
		return $a;
	}
	/** 
	* 应用加载
	*/ 
	private static function loadComm() 
	{
		//调试模式设置错误报告级别并进行环境检查
		if (Config::get('app','de')=='true') {
			ini_set('display_errors', 'On'); // 开启显示错误
			error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
		} else {
			ini_set('display_errors', 'Off'); // 关闭显示错误
			error_reporting(E_ERROR);
			ini_set('error_log',RUNTIME_PATH . 'log' . DS . date("Y-m-d") . '-error.log');
		}
	}
	/** 
	* 实例方法 
	* @param string	$a['c']	控制器
	* @param string	$a['c']	方法
	* @echo string	
	*/ 
	private static function loadController($a) 
	{
		$c = str_replace('/',DS,$a['c']) . 'Controller';
		Response::checkFile(APP_CONTROLLER_PATH . $c . '.php');
		$c = APP_CONTROLLER .$c;
        $c = new $c;
        $c->make($c,$a['f']);
	}
}
?>